package org.example.shop.service.impl;

import org.example.shop.config.RabbitMQConfig;
import org.example.shop.service.RabbitMQService;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class RabbitMQServiceImpl implements RabbitMQService {

    private RabbitTemplate rabbitTemplate;

    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }


    @Override
    public boolean sendMessage(String message, int delay) {
        try {
            String msgId = UUID.randomUUID().toString().replace("-", "").substring(0, 32);

            Map<String, Object> map = new HashMap<>();
            map.put("id", msgId);
            map.put("sendTime", System.currentTimeMillis());
            map.put("message", message);
            // 发送
            rabbitTemplate.convertAndSend(RabbitMQConfig.RABBITMQ_DEFAULT_DIRECT_EXCHANGE,
                    RabbitMQConfig.RABBITMQ_DEFAULT_DIRECT_ROUTING, map, new MessagePostProcessor() {
                        @Override
                        public Message postProcessMessage(Message message) throws AmqpException {
                            //给消息设置延迟毫秒值
                            message.getMessageProperties().setExpiration(String.valueOf(delay));
                            return message;
                        }
                    });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
